package com.foreverwin.jzymes.framework.util;

import com.foreverwin.jzymes.framework.exception.BusinessException;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateUtil {

    private static String DATE_FORMAT1 = "yyyy-MM-dd HH:mm:ss.SSS";
    private static String DATE_FORMAT2 = "yyyy/MM/dd HH:mm:ss.SSS";
    private static String DATE_FORMAT3 = "yyyy-MM-dd HH:mm:ss";
    private static String DATE_FORMAT4 = "yyyy/MM/dd HH:mm:ss";
    private static String DATE_FORMAT5 = "yyyy-MM-dd";
    private static String DATE_FORMAT6 = "yyyy/MM/dd";

    public static String format( Date date, String pattern ){
        SimpleDateFormat dateFormat = new SimpleDateFormat( pattern );
        return dateFormat.format( date );
    }

    public static String format( Date date ){
        return format( date, DATE_FORMAT1 );
    }

    public static Date parse( String date, String pattern ) {
        try {
            SimpleDateFormat dateFormat = new SimpleDateFormat( pattern );
            return dateFormat.parse( date );
        } catch (ParseException e) {
            throw BusinessException.build( "common.dateFormatNotSupport", new String[]{ date } );
        }
    }

    public static Date parse( String date ){
        if( date.length() == 23 ){
            if( date.indexOf( "/" ) > -1 ){
                return parse( date, DATE_FORMAT2 );
            }else if( date.indexOf( "-" ) > -1 ){
                return parse( date, DATE_FORMAT1 );
            }
        }
        if( date.length() == 19 ){
            if( date.indexOf( "/" ) > -1 ){
                return parse( date, DATE_FORMAT4 );
            }else if( date.indexOf( "-" ) > -1 ){
                return parse( date, DATE_FORMAT3 );
            }
        }
        if( date.length() == 10 ){
            if( date.indexOf( "/" ) > -1 ){
                return parse( date, DATE_FORMAT6 );
            }else if( date.indexOf( "-" ) > -1 ){
                return parse( date, DATE_FORMAT5 );
            }
        }
        throw BusinessException.build( "common.dateFormatNotSupport", new String[]{ date } );
    }

    public static Date addDays( Date date, int days ){
        Date date1 = (Date) date.clone();
        date1.setTime( date.getTime() + days * 24 * 60 * 60 * 1000 );
        return date1;
    }

    public static Date addHours( Date date, int hours ){
        Date date1 = (Date) date.clone();
        date1.setTime( date.getTime() + hours * 60 * 60 * 1000 );
        return date1;
    }

    public static Date addMinutes( Date date, int minutes ){
        Date date1 = (Date) date.clone();
        date1.setTime( date.getTime() + minutes * 60 * 1000 );
        return date1;
    }
}
